package com.asp.alumnisystem.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.asp.alumnisystem.utils.ListUtils;
import com.asp.alumnisystem.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * BaseActivity
 */
public abstract class BaseActivity extends AppCompatActivity {

    private Unbinder unbinder;
    private List<BasePresenter> presenterList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (interceptCreate(savedInstanceState)){
            finish();
            return;
        }
        View view = getLayoutView();
        if (view != null){
            setContentView(view);
        }else{
            setContentView(getLayoutId());
        }
        if (useButterKnife()){
            unbinder = ButterKnife.bind(this);
        }
        initView();
    }

    public void managerPresenter(BasePresenter presenter){
        if (presenter == null){
            return;
        }
        if (presenterList == null){
            presenterList = new ArrayList<>();
        }
        presenterList.add(presenter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ListUtils.isNotNull(presenterList)){
            for (BasePresenter basePresenter : presenterList) {
                basePresenter.destroy();
            }
            presenterList.clear();
        }
        if (unbinder != null){
            unbinder.unbind();
        }
    }

    @Override
    public void onBackPressed() {
        onBack();
    }

    /**
     * 是否拦截onCreate方法
     * 返回true表示拦截的 则直接finish
     */
    protected boolean interceptCreate(Bundle savedInstanceState){
        return false;
    }

    protected View getLayoutView(){
        return null;
    }
    /**
     * 返回view的id
     */
    protected abstract int getLayoutId();

    /**
     * 返回view的id
     */
    public abstract void onBack();

    /**
     * 初始化界面
     */
    protected void initView(){}

    /**
     * 是否使用 Butterknife
     */
    protected boolean useButterKnife(){
        return true;
    }


    public void loadStart(BasePresenter presenter) {
    }

    public void loadFail(BasePresenter presenter, String error) {
        if (getBaseAdapter() != null){
            getBaseAdapter().dataChange();
        }
        ToastUtil.showShortToast(error);
    }

    public void loadDone(BasePresenter presenter) { }

    /**
     * 获取实现类的baseAdapter，用于在请求失败是显示界面不同状态
     */
    public BaseAdapter getBaseAdapter(){
        return null;
    }

}
